package com.ruoyi.web.controller.book;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.YgabcBookInfo;
import com.ruoyi.system.service.IYgabcBookInfoService;
import org.apache.ibatis.jdbc.Null;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.YgabcBorrow;
import com.ruoyi.system.service.IYgabcBorrowService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * ygabc_borrowController
 *
 * @author ruoyi
 * @date 2022-06-15
 */
@RestController
@RequestMapping("/system/borrow")
@Component("Test")
public class YgabcBorrowController extends BaseController {
    @Autowired
    private IYgabcBorrowService ygabcBorrowService;
    @Autowired
    private IYgabcBookInfoService ygabcBookInfoService;

    /**
     * 查询ygabc_borrow列表
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:list')")
    @GetMapping("/list")
    public TableDataInfo list(YgabcBorrow ygabcBorrow) throws Exception {
        long Days = 0;
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String returntime = df.format(date);
        Long userId = SecurityUtils.getLoginUser().getUserId();
        int userid = Math.toIntExact(userId);
        List<YgabcBorrow> list = ygabcBorrowService.selectYgabcBorrowList(ygabcBorrow);
        for (YgabcBorrow y : list
        ) {
            String borrowtime = df.format(y.getBorrowTime());
            long time = df.parse(returntime).getTime();
            long time1 = df.parse(borrowtime).getTime();
            Days = (int) ((time - time1) / (24 * 60 * 60 * 1000));
            double days = Days;
            if (days >= 14) {
                y.setStatus(Long.valueOf("2"));
                ygabcBorrowService.updateYgabcBorrow(y);
            }
            Date returnTime = y.getReturnTime();
            if(returnTime!=null){
                y.setStatus(Long.valueOf("0"));
                ygabcBorrowService.updateYgabcBorrow(y);
            }
        }
        startPage();
        if (userid != 1 && userid != 105) {
            String userid1 = String.valueOf(userid);
            List<YgabcBorrow> list1 = ygabcBorrowService.selectYgabcBorrowByuserId(userid1);
            return getDataTable(list1);
        } else {
            return getDataTable(list);
        }
    }

    /**
     * 导出ygabc_borrow列表
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:export')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YgabcBorrow ygabcBorrow) {
        List<YgabcBorrow> list = ygabcBorrowService.selectYgabcBorrowList(ygabcBorrow);
        ExcelUtil<YgabcBorrow> util = new ExcelUtil<YgabcBorrow>(YgabcBorrow.class);
        util.exportExcel(response, list, "ygabc_borrow数据");
    }

    /**
     * 获取ygabc_borrow详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(ygabcBorrowService.selectYgabcBorrowById(id));
    }

    /**
     * 新增ygabc_borrow
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:add')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YgabcBorrow ygabcBorrow) throws Exception {
        YgabcBookInfo ygabcBookInfo = ygabcBookInfoService.selectYgabcBookInfoById(ygabcBorrow.getBookId());
        Long num = ygabcBookInfo.getNum();
        if (num == 0) {
            throw new Exception("图书数量不足");
        }
        Long num1 = num - 1;
        ygabcBookInfo.setNum(num1);
        ygabcBookInfoService.updateYgabcBookInfo(ygabcBookInfo);
        return toAjax(ygabcBorrowService.insertYgabcBorrow(ygabcBorrow));
    }

    /**
     * 修改ygabc_borrow
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:edit')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YgabcBorrow ygabcBorrow) {
        return toAjax(ygabcBorrowService.updateYgabcBorrow(ygabcBorrow));
    }

    /**
     * 删除ygabc_borrow
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:remove')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(ygabcBorrowService.deleteYgabcBorrowByIds(ids));
    }

    /**
     * 借书
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:borrow')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.INSERT)
    @PostMapping("/borrow/{bookid}")
    @RepeatSubmit
    public AjaxResult borrow(@PathVariable("bookid") String bookid) throws Exception {
        YgabcBorrow borrow = new YgabcBorrow();
        String userid = String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId());
        borrow.setBookId(bookid);
        borrow.setUserId(userid);
        borrow.setBorrowTime(new Date(System.currentTimeMillis()));
        borrow.setStatus(Long.valueOf("1"));
        YgabcBookInfo ygabcBookInfo = ygabcBookInfoService.selectYgabcBookInfoById(bookid);
        Long num = ygabcBookInfo.getNum();
        if (num == 0) {
            throw new Exception("图书数量不足");
        }
        Long num1 = num - 1;
        ygabcBookInfo.setNum(num1);
        ygabcBookInfoService.updateYgabcBookInfo(ygabcBookInfo);
        return toAjax(ygabcBorrowService.insertYgabcBorrow(borrow));
    }

    /**
     * 还书
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:return')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.UPDATE)
    @PutMapping("/returnbook/{borrowid}")
    @RepeatSubmit
    public AjaxResult returnbook(@PathVariable("borrowid") String borrowid) {
        YgabcBorrow borrow = ygabcBorrowService.selectYgabcBorrowById(borrowid);
        borrow.setReturnTime(new Date(System.currentTimeMillis()));
        borrow.setStatus(Long.valueOf("0"));
        String bookid = borrow.getBookId();
        YgabcBookInfo ygabcBookInfo = ygabcBookInfoService.selectYgabcBookInfoById(bookid);
        Long num = ygabcBookInfo.getNum();
        Long num1 = num + 1;
        ygabcBookInfo.setNum(num1);
        ygabcBookInfoService.updateYgabcBookInfo(ygabcBookInfo);
        return toAjax(ygabcBorrowService.updateYgabcBorrow(borrow));
    }

    /**
     * 还书
     */
    @PreAuthorize("@ss.hasPermi('system:borrow:rent')")
    @Log(title = "ygabc_borrow", businessType = BusinessType.UPDATE)
    @PutMapping("/rentbook/{borrowid}")
    @RepeatSubmit
    public AjaxResult rentbook(@PathVariable("borrowid") String borrowid) {
        YgabcBorrow borrow = ygabcBorrowService.selectYgabcBorrowById(borrowid);
        Long status = borrow.getStatus();
        int truestatus = Math.toIntExact(status);
        if (truestatus == 2) {
            borrow.setBorrowTime(new Date(System.currentTimeMillis()));
            borrow.setStatus(Long.valueOf("1"));
            return toAjax(ygabcBorrowService.updateYgabcBorrow(borrow));
        }
        return toAjax(ygabcBorrowService.updateYgabcBorrow(borrow));
    }
}
